package handler

import (
	"github.com/gin-gonic/gin"
	"news-mnger/models"
	"strconv"
)

func NewsAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.News{

		Title:   title,
		Content: content,
		Img:     img,
		UserID:  userID,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "新闻增加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "新闻增加成功",
	})
	return

}

func NewList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.News{}).Count(&count)

	var news []models.News
	err := models.DB.Offset(offset).Limit(size).Find(&news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": gin.H{
			"count": count,
			"data":  news,
		},
	})
	return

}
